package com.zl.gen;

import com.zl.util.Exceptions;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.FileResourceLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ClassUtils;

import java.io.IOException;
import java.util.Map;


public class GroupTempalteUtil {

    private static final Logger logger = LoggerFactory.getLogger(GroupTempalteUtil.class);

    private static GroupTemplate groupTemplate = getGroupTemplate("template/");

    /**
     * 绝对路径
     */
    public static final String ROOT_PATH_JD = ClassUtils.getDefaultClassLoader().getResource("").getPath();


    /**
     * 加载beetl文件,返回 Tempalte
     *
     * @param path
     * @return
     */
    private static GroupTemplate getGroupTemplate(String path) {
        try {
            String root = ClassUtils.getDefaultClassLoader().getResource("").getPath() + path;


            FileResourceLoader resourceLoader = new FileResourceLoader(root, "utf-8");
            Configuration cfg = Configuration.defaultConfiguration();
            GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
            return gt;
        } catch (IOException e) {
            logger.error("构建 GroupTemplate 对象异常，异常原因：{}", Exceptions.getStackTraceAsString(e));
        }
        return null;
    }

    private static Template getTempalte(String templateName) {
        if (groupTemplate == null) {
            return null;
        }
        return groupTemplate.getTemplate(templateName);
    }


    public static String bindingAndRenderByMap(String templateName, Map<String, Object> map) {
        try {
            Template template = getTempalte(templateName);
            if (template == null) {
                logger.error("获取的Template对象为空，请检查...");
                return null;
            }
            synchronized (template) {
                template.binding(map);
                return template.render();
            }
        } catch (Exception e) {
            logger.error("绑定以及输出结果出现异常，异常原因：{}", Exceptions.getStackTraceAsString(e));
        }
        return null;
    }
}
